package com.zweirm.lagee_quizing_web.config;

import com.zweirm.lagee_quizing_web.handler.BrowserAuthenticationFailureHandler;
import com.zweirm.lagee_quizing_web.handler.BrowserAuthenticationSuccessHandler;
import com.zweirm.lagee_quizing_web.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 浏览器安全配置类
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private BrowserAuthenticationSuccessHandler browserAuthenticationSuccessHandler;

    @Autowired
    private BrowserAuthenticationFailureHandler browserAuthenticationFailureHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(securityProperties.getBrowserProperties().getLoginPage(),
                        "/login.html",
                        "/backLogin.html",
                        "/register.html",
                        "/403.html",
                        "/404.html",
                        "/500.html",

                        "/authentication/require",
                        "/register",
                        "/doRegister",
                        "/backLogin",
                        "/session/invalid",
                        "/checkUserExist",
                        "/fonts/*",

                        "/static/**",
                        "/fonts/**",
                        "/css/**",
                        "/img/**",
                        "/js/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form")
                .successHandler(browserAuthenticationSuccessHandler)
                .failureHandler(browserAuthenticationFailureHandler)
                .and()
            .sessionManagement()
                .invalidSessionUrl("/session/invalid")
                .and()
            .csrf().disable();
    }
}
